<template>
  <div :class="[prefixCls, { fullscreen }]">
    <Upload
      name="file"
      multiple
      @change="handleChange"
      :action="uploadUrl"
      :showUploadList="false"
      :data="getBizData()"
      :headers="getheader()"
      :before-upload="beforeUpload"
      accept=".jpg,.jpeg,.png,.gif,.bmp,.webp,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt,.mp3,.wav,.ogg,.flac,.aac,.mp4,.avi,.mov,.wmv,.flv,.mkv"
    >
      <a-button type="primary" v-bind="{ ...getButtonProps }">
        {{ t('component.upload.fileUpload') }}
      </a-button>
    </Upload>
  </div>
</template>
<script lang="ts">
  import { defineComponent, computed, ref } from 'vue';

  import { Upload } from 'ant-design-vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getFileAccessHttpUrl, getHeaders } from '/@/utils/common/compUtils';

  export default defineComponent({
    name: 'TinymceFileUpload',
    components: { Upload },
    props: {
      fullscreen: {
        type: Boolean,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['uploading', 'done', 'error', 'loading'],
    setup(props, { emit }) {
      const { createMessage } = useMessage();
      
      function getheader() {
        return getHeaders();
      }

      function getBizData() {
        return {
          biz: 'richtext',
          type: 'attachment',
        };
      }
      const { domainUrl } = useGlobSetting();
      const uploadUrl = domainUrl + '/sys/fileRecord/uploadRichTextFile';
      //文件列表
      let uploadFileList = ref<any[]>([]);
      const { t } = useI18n();
      const { prefixCls } = useDesign('tinymce-file-upload');

      const getButtonProps = computed(() => {
        const { disabled } = props;
        return {
          disabled,
        };
      });

      let uploadLength = 0;
      function handleChange({ file, fileList }) {
        // 过滤掉已经存在的文件
        fileList = fileList.filter((file) => {
          const existFile = uploadFileList.value.find(({ uid }) => uid === file.uid);
          return existFile ? false : true;
        });
        uploadLength == 0 && (uploadLength = fileList.length);
        if (file.status != 'uploading') {
          emit('loading', uploadLength, true);
        }
        // 处理上传好的文件
        if (file.status != 'uploading') {
          fileList.forEach((file) => {
            if (file.status === 'done' && file.response.success) {
              const name = file?.name;
              let realUrl = getFileAccessHttpUrl(file.response.result);
              uploadFileList.value.push(file);
              emit('done', name, realUrl);
            }
          });
        }
      }
      //上传之前
      function beforeUpload(file) {
        // 检查文件大小
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          createMessage.error('文件大小不能超过10MB!');
          return false;
        }
        
        // 检查文件类型
        const fileName = file.name;
        const extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        const allowedTypes = [
          // 图片
          'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp',
          // 文档
          'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'txt',
          // 音频
          'mp3', 'wav', 'ogg', 'flac', 'aac',
          // 视频
          'mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'
        ];
        
        if (!allowedTypes.includes(extension)) {
          createMessage.error('不支持的文件类型!');
          return false;
        }
        
        uploadLength = 0;
        emit('loading', null, true);
        setTimeout(() => {
          emit('loading', null, false);
        }, 10000);
        return true;
      }
      return {
        prefixCls,
        handleChange,
        uploadUrl,
        getheader,
        getBizData,
        t,
        getButtonProps,
        uploadFileList,
        beforeUpload,
      };
    },
  });
</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-tinymce-file-upload';

  .@{prefix-cls} {
    position: absolute;
    right: 10px;
    z-index: 20;

    .ant-upload-button {
      width: 20px;
      min-width: 20px;
      height: 20px;
      font-size: 12px;
      line-height: 20px;
      padding: 0 0 0 1px;
      background-color: @primary-color;
      border-color: @primary-color;
      border-radius: 2px;
    }

    &.fullscreen {
      position: fixed;
      z-index: 9999;
      top: 100px;
      right: 80px;
    }
  }
</style> 